package com.han.hotelplat.interceptor;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.jpush.api.common.resp.ResponseWrapper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.ResponseWrapTo;
import com.han.hotelplat.comm.utils.DateUtil;

public class Interceptor extends HandlerInterceptorAdapter {

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// 请求处理完成之后
		System.out.println("请求处理完成啦！");
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// 处理器执行完毕之后
		System.out.println("处理器执行完毕啦！");
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 处理器实际执行之前
		System.out.println(String.format("%s : 处理器执行之前！url:%s", DateUtil.format(new Date(), DateUtil.YMDHMS), request.getRequestURI()));
		String url = request.getRequestURL().toString();
		String headUrl = url.substring(0,url.lastIndexOf("/"));
		String fileName = url.substring(url.lastIndexOf("/"));
		String redirectURL = headUrl+"/source/"+fileName;
		Object beiang_img_size = request.getParameter("beiang_img_size");
		//Object user = request.getSession().getValue(Constant.SESSION_LOGIN_USER);
		/*if (user == null) {
			// 未通过验证，返回提示json
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			response.getWriter().write(new ResponseWrapTo(-99, "用户信息过期请重新登录", null).toJson());
			return false;
		}*/
		if(beiang_img_size != null && "1".equals(beiang_img_size.toString())){
			
			try {
				   response.setCharacterEncoding("utf-8");
				   response.sendRedirect(redirectURL);
				   return true;
				} catch (IOException e) {
					 e.printStackTrace();
				}
		}
		return super.preHandle(request, response, handler);
	}

}
